#!/usr/bin/env python3
"""
Git post-commit hook
在每次提交后自动更新 Unreleased 部分
"""

import os
import sys
from pathlib import Path
import subprocess
import re

def update_unreleased_section():
    """更新 Unreleased 部分"""
    changelog_path = Path("CHANGELOG.md")
    
    if not changelog_path.exists():
        return
    
    # 获取最新提交信息
    try:
        result = subprocess.run(
            ['git', 'log', '-1', '--pretty=format:%s'],
            capture_output=True,
            text=True,
            check=True,
            encoding='utf-8',
            errors='ignore'
        )
        commit_message = result.stdout.strip() if result.stdout else ""
    except subprocess.CalledProcessError:
        return
    
    if not commit_message:
        return
    
    # 解析提交类型
    change_types = {
        'feat': 'Added',
        'add': 'Added', 
        'fix': 'Fixed',
        'bug': 'Fixed',
        'docs': 'Changed',
        'style': 'Changed',
        'refactor': 'Changed',
        'remove': 'Removed',
        'security': 'Security',
        'deprecate': 'Deprecated'
    }
    
    # 解析提交消息
    pattern = r'^(\w+)(?:\(([^)]+)\))?\s*:\s*(.+)$'
    match = re.match(pattern, commit_message)
    
    if match:
        commit_type = match.group(1).lower()
        scope = match.group(2) or ''
        description = match.group(3)
    else:
        # 默认为 Changed
        commit_type = 'change'
        scope = ''
        description = commit_message
    
    category = change_types.get(commit_type, 'Changed')
    
    # 读取现有 changelog
    content = changelog_path.read_text(encoding='utf-8')
    
    # 在对应类别下添加新条目
    scope_str = f"**{scope}**: " if scope else ""
    new_entry = f"- {scope_str}{description}\n"
    
    # 找到 Unreleased 部分的对应类别
    category_pattern = f"(### {category}\\n\\n)"
    match = re.search(category_pattern, content)
    
    if match:
        # 在类别后添加新条目
        insert_pos = match.end()
        content = content[:insert_pos] + new_entry + content[insert_pos:]
        
        # 写回文件
        changelog_path.write_text(content, encoding='utf-8')
        print(f"已将提交添加到 Changelog 的 {category} 部分")


if __name__ == '__main__':
    update_unreleased_section()